using B.S.RbacData.ErrorCode;
using MediatR;
using SupplierCustomerManagement.Write.API.Applications.Commands.attachments;
using SupplierCustomerManagement.Write.API.Services;
using SupplierCustomerManagement.Infrastructure;
using SupplierCustomerManagement.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using B.S.RbacData.Infrastructure;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.attachments
{
    /// <summary>
    /// 删除附件命令处理器
    /// </summary>
    public class DeleteAttachmentCommandHandler : IRequestHandler<DeleteAttachmentCommand, ApiResult<bool>>
    {
        private readonly IMinioService _minioService;
        private readonly IBaseRepository<Attachment> _attachmentRepository;
        private readonly ILogger<DeleteAttachmentCommandHandler> _logger;

        public DeleteAttachmentCommandHandler(
            IMinioService minioService,
            IBaseRepository<Attachment> attachmentRepository,
            ILogger<DeleteAttachmentCommandHandler> logger)
        {
            _minioService = minioService;
            _attachmentRepository = attachmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除附件命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteAttachmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理删除附件命令，附件ID：{AttachmentId}", request.Id);

                // 查找附件
                var attachment =  _attachmentRepository.GetAll().FirstOrDefault(x=>x.Id== request.Id);
                if (attachment == null)
                {
                    _logger.LogWarning("附件不存在，ID：{AttachmentId}", request.Id);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "附件不存在",
                        data = false
                    };
                }

                if (attachment.IsDeleted)
                {
                    _logger.LogWarning("附件已被删除，ID：{AttachmentId}", request.Id);
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "附件已被删除",
                        data = false
                    };
                }

                // 如果请求删除存储中的文件
                if (request.DeleteFromStorage && !string.IsNullOrEmpty(attachment.FilePath))
                {
                    try
                    {
                        // 从文件路径中提取存储桶和对象名称
                        var uri = new Uri(attachment.FilePath);
                        var pathSegments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
                        
                        if (pathSegments.Length >= 2)
                        {
                            var bucketName = pathSegments[0];
                            var objectName = string.Join("/", pathSegments.Skip(1));
                            
                            await _minioService.DeleteFileAsync(bucketName, objectName);
                            _logger.LogInformation("成功从存储中删除文件，存储桶：{BucketName}，对象名称：{ObjectName}", 
                                bucketName, objectName);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "从存储中删除文件失败，文件路径：{FilePath}", attachment.FilePath);
                        // 继续执行，不因为存储删除失败而阻止数据库记录删除
                    }
                }

                // 软删除数据库记录
                attachment.IsDeleted = true;
                attachment.UpdatedTime = DateTime.Now;
                attachment.UpdatedBy = request.DeletedBy;

                await _attachmentRepository.UpdateAsync(attachment);
               

                _logger.LogInformation("附件删除成功，ID：{AttachmentId}，文件名：{FileName}", 
                    attachment.Id, attachment.FileName);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.Ok,
                    message = "附件删除成功",
                    data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除附件过程中发生异常，附件ID：{AttachmentId}", request.Id);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"删除附件失败：{ex.Message}",
                    data = false
                };
            }
        }
    }
} 